package org.addressBook.servlet;

import org.addressBook.bean.TbUser;
import org.addressBook.service.TbUserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet {

    private TbUserService us = new TbUserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        // 获取从前端传递过来的用户名与密码
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        request.getSession().setAttribute("name", name);
        // 校验用户信息是否为空
        if ("".equals(name) || "".equals(password)) {
            out.print("用户名或密码未填！");
            request.getRequestDispatcher("/index.jsp").include(request, response);
            return;
        }
        // 执行查询
        TbUser user = null;
        try {
            user = us.login(name, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (user == null) {
            out.print("用户名或密码不正确，请重新登录");
            request.getRequestDispatcher("/index.jsp").include(request, response);
        } else {
            // 校验用户信息是否为空
            try {
                us.loadAddressBook(name,password);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            request.getRequestDispatcher("/manage.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
